package tech.aistar.controller.applyTourist;

import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import tech.aistar.entity.User.CodeStatus;
import tech.aistar.entity.User.Register;
import tech.aistar.entity.User.UserResult;
import tech.aistar.entity.authordis.UserTable;
import tech.aistar.entity.daoyou.GuideApply;
import tech.aistar.entity.daoyou.GuideCodeStatus;
import tech.aistar.entity.daoyou.GuideResult;
import tech.aistar.entity.daoyou.UserIdcard;
import tech.aistar.exception.LogginException;
import tech.aistar.mapper.guidemapper.Guide;
import tech.aistar.service.applyTouristService.IApplyTouristService;
import tech.aistar.util.Random_util;
import tech.aistar.util.UploadImg.QiniuCloudUtil;
import tech.aistar.util.verified.PhontoApi;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created by lenovo on 2019/10/7.
 */

@Controller
public class ApplyTourist {

    @Autowired
    private IApplyTouristService applyTouristService;

    @Autowired
    JavaMailSenderImpl mailSender;

    @RequestMapping("/applytourist")
    public String returnLogin(Model model, HttpServletRequest request) {

        HttpSession session = request.getSession();
        UserTable userTable = (UserTable) session.getAttribute("userId");
        model.addAttribute("userTable", userTable);
        return "applyTourist/applyTourist";
    }



    //   Ajax 验证手机号码
    @GetMapping("/checkphone")
    public @ResponseBody
    UserResult checkPhone(UserTable userTable) throws LogginException {

        UserTable u = applyTouristService.findByPhone(userTable.getPhone());
        if (null == u) {

            return new UserResult(CodeStatus.OK, true, "该手机号还未注册为用户", null);
        } else {
            return new UserResult(CodeStatus.ERROR, false, "", null);
        }
    }

    //给用户发送邮件
    @PostMapping("/sendcode")
    public void code(Register user) {


        SimpleMailMessage message = new SimpleMailMessage();
        StringBuffer ver_code = Random_util.getRandom();

        applyTouristService.insertregister(user.getPhone(), user.getEmail(), String.valueOf(ver_code));
        message.setSubject("Uyou网-验证邮件");
        message.setText("本邮件为申请成为Uyou网导游的验证码:" + String.valueOf(ver_code));
        message.setTo(user.getEmail());
        message.setFrom("2505617950@qq.com");

        mailSender.send(message);

    }

    //失去焦点后检测验证码
    @GetMapping("/checkcode")
    public @ResponseBody
    UserResult checkCode(Register user) {
        Register u = applyTouristService.findByCode(user.getVerCode(), user.getPhone());
        if (null == u) {

            return new UserResult(CodeStatus.ERROR, false, "验证码错误", null);
        } else {
            return new UserResult(CodeStatus.OK, true, "", null);
        }
    }

    @RequestMapping("/insertGuide")
    @ResponseBody
    public void insert(String phone, String address, String profile, String photo) {
        System.out.println(address);
        System.out.println(phone);
        System.out.println(photo);
        System.out.println(profile);

        UserTable u = applyTouristService.findId(phone);
        System.out.println(u);
        Integer id = null;
        if (u != null) {
            id = u.getId();

            UserIdcard user = applyTouristService.findById(id);
            System.out.println(user);
            String name = null;
            String birthplace = null;
            String sex = null;

            name = user.getName();
            birthplace = user.getBirth();
            sex = user.getSex();
            if (name != null && birthplace != null && sex != null) {

                applyTouristService.insert(address, phone, id, name, birthplace, sex);

                GuideApply guide = applyTouristService.findGuideId(name);
                Integer guideId = guide.getId();

                applyTouristService.saveGuideInfo(guideId, photo, profile);
            }


        }
//        return "redirect:/guide/index";

    }

    @RequestMapping(value = "/addUser")
    @ResponseBody
    public Map addUser(HttpServletRequest request, MultipartFile myfile2) throws Exception {

        Map<String, String> map = new HashMap<>();

        //使用UUID给图片重命名，并去掉四个“-”
        String name = UUID.randomUUID().toString().replaceAll("-", "");
        //获取文件的扩展名
        String ext = FilenameUtils.getExtension(myfile2.getOriginalFilename());
        //设置图片上传路径
        String url = request.getSession().getServletContext().getRealPath("/imgs/upload");
        //以绝对路径保存重名命后的图片
        myfile2.transferTo(new File(url + "/" + name + "." + ext));
        //拼接绝对路径到页面,回显数据
        String imgUrl = ("imgs/upload/" + name + "." + ext);

        //获取最后的路径,验证身份信息
        String path = request.getSession().getServletContext().getRealPath("/imgs/upload/" + name + "." + ext);


        //放入map数据回显
        map.put("path", path);
        map.put("imgUrl", imgUrl);
        if (imgUrl != null) {
            return map;
        } else {
            return map;
        }
    }


    @RequestMapping("/verified")
    @ResponseBody
    public GuideResult verified(@RequestParam String paths, Model model, Integer userId) {
        System.out.println(paths);


        HashMap<String, String> map = null;
        try {
            map = PhontoApi.checkPhone(paths);
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println(map);
        if (map.size() > 0) {

            UserIdcard user = applyTouristService.findUser(map.get("name"));
            if (null != user) {
                return new GuideResult(GuideCodeStatus.OK, false, "该用户已经实名认证");
            }
            applyTouristService.save(userId, map.get("name"), map.get("address"), map.get("Birth"), map.get("IDCard"), map.get("nation"), map.get("sex"));
            return new GuideResult(GuideCodeStatus.OK, true, "信息正确", map);
        } else {
            return new GuideResult(GuideCodeStatus.OK, false, "图片格式错误重新上传");
        }


    }

//    @RequestMapping("/verified")
//    @ResponseBody
//    public Map upload(MultipartFile myfile) {
//        Map<String,String> map = new HashMap<>();
//
//        try {
//            String imgUrl = QiniuCloudUtil.upload(myfile.getBytes(),myfile.getOriginalFilename());
//            map.put("imgUrl", imgUrl);
//
//        } catch (IOException e) {
//            e.printStackTrace();
//            map.put("imgUrl", null);
//
//        }
//        //因为要作为结果返回
//        System.out.println(map);
//        return map;
//
//    }

}